package com.zl.tby.icc;

import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * 发起ICC的https请求
 * @author changpeng
 * @version 1.0
 * @since 2024/9/5 9:20
 */
public class IccHttpsURLConnectionUtil {
    static {
        try {
            trustAllHttpsCertificates();
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                public boolean verify(String urlHostName, SSLSession session) {
                    return true;
                }
            });
        } catch (Exception e) {
        }
    }

    private static void trustAllHttpsCertificates() throws NoSuchAlgorithmException,     KeyManagementException {
        TrustManager[] trustAllCerts = new TrustManager[1];
        trustAllCerts[0] = new TrustAllManager();
        /** JDK1.7是TLS1.0，而JDK1.8是TLSv1.2，要调用ICC框架版本是JDK8，因此这里设置为TLSv1.2 **/
        SSLContext sc = SSLContext.getInstance("TLSv1.2");
        sc.init(null, trustAllCerts, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    }

    private static class TrustAllManager implements X509TrustManager {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
        public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {}
        public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {}
    }

    /**
     * get请求
     * @param request：请求
     * @return 返回的json字符串
     */
    public static String doGet(String httpUrl, HttpRequestHeader...headers) {
        StringBuilder response = new StringBuilder();
        BufferedReader bufferedReader = null;

        try{
            //创建连接
            URL url = new URL(httpUrl);
            HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
            //忽略ssl验证
            //disableSslVerification(connection);
            //设置请求方式
            connection.setRequestMethod("GET");
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("content-type", "application/x-www-form-urlencoded;charset=UTF-8");
            //设置自定义请求头信息
            setCustomHeader(connection, headers);

            //设置请求超时时间:10秒
            connection.setConnectTimeout(10 * 1000);
            //设置读取超时时间:10秒
            connection.setReadTimeout(10 * 1000);
            //开始连接
            connection.connect();

            //获取响应数据
            String readLine = null;
            bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
            while((readLine = bufferedReader.readLine()) != null){
                response.append(readLine);
            }
            bufferedReader.close();
        }catch (MalformedURLException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
        return response.toString();
    }

    /**
     * post请求
     * @param httpUrl: 请求地址
     * @param body：请求体
     * @param headers：请求头
     * @return 结果
     */
    public static String doPost(String httpUrl, String body, HttpRequestHeader...headers) {
        StringBuilder response = new StringBuilder();
        BufferedReader bufferedReader = null;

        try{
            //创建连接
            URL url = new URL(httpUrl);
            HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
            //忽略ssl验证
            //disableSslVerification(connection);

            //设置请求方式
            connection.setRequestMethod("POST");
            connection.setRequestProperty("accept", "application/json");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("content-type", "application/json;charset=UTF-8");
            //设置自定义请求头信息
            setCustomHeader(connection, headers);

            connection.setDoOutput(true);
            connection.setDoInput(true);
            //设置请求超时时间:10秒
            connection.setConnectTimeout(10 * 1000);
            //设置读取超时时间:10秒
            connection.setReadTimeout(10 * 1000);
            //设置请求参数
            if(body != null && !"".equalsIgnoreCase(body)){
                OutputStream outputStream = connection.getOutputStream();
                byte[] input = body.getBytes("utf-8");
                outputStream.write(input, 0, input.length);
                outputStream.flush();
                outputStream.close();
            }
            connection.connect();

            //获取响应数据
            String readLine = null;
            bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
            while((readLine = bufferedReader.readLine()) != null){
                response.append(readLine);
            }
            bufferedReader.close();
        }catch (MalformedURLException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }

        return response.toString();
    }

    /**
     * 设置自定义请求头信息
     * @param connection: 连接
     * @param header：请求头
     */
    public static void setCustomHeader(HttpURLConnection connection, HttpRequestHeader...header) {
        if (header != null) {
            for (HttpRequestHeader httpRequestHeader : header) {
                connection.setRequestProperty(httpRequestHeader.getName(), httpRequestHeader.getValue());
            }
        }
    }
}
